function [gbestX,gbestfitness,gbesthistory]=CSO(popsize,D,xmax,xmin,vmax,vmin,maxIter,FuncId)

%% initialization
lu = [xmin * ones(1, D); xmax * ones(1, D)];
XRRmin=repmat(lu(1, :),popsize,1);
XRRmax=repmat(lu(2, :),popsize,1);

%% Chaotic Initialization
v=zeros(popsize,D);
xl=rand(popsize,D);
% for i=1:popsize-1
%     for j=1:D
%          xl(i+1,j)=xl(i,j)+0.2-mod((0.5/(2.*pi)).*sin(2.*pi.*xl(i,j)),1);
%      end
% end
p = XRRmin + (XRRmax - XRRmin) .* xl;%???位置
%fitness =  SimpleBenchmark(p,FuncId);
fitness = SimpleBenchmark(p,FuncId);%测试函数，可以更改为其他函数

%% Set parameters
gbestfitness = 1e200;%10的200次方
phi = 0.5;
gbesthistory=rand(maxIter,1);
gbestX=rand(1,D);

%% Cauchy Mutation
original_x=rand();
cauchy_x=tan((original_x-1/2)*pi);

%% main loop
for gen=1 :maxIter
    % generate random pairs
    rlist = randperm(popsize);%随机选pop个
  rpairs = [rlist(1:ceil(popsize/2)); rlist(floor(popsize/2) + 1:popsize)]';%？？？进行配对
%        rpairs = [rlist(1:ceil(popsize/3)); rlist(floor(popsize/3) + 1:popsize);]';%？？？进行配对

    % calculate the center position
   center = ones(ceil(popsize/2),1)*mean(p);
%      center = ones(ceil(popsize/3),1)*mean(p);
    % do pairwise competitions
    mask = (fitness(rpairs(:,1)) > fitness(rpairs(:,2)));%第一列大于第二列
    losers = mask.*rpairs(:,1) + ~mask.*rpairs(:,2);
    winners = ~mask.*rpairs(:,1) + mask.*rpairs(:,2);
    
    %random matrix 随机矩阵
    randco1 = rand(ceil(popsize/2),D);
    randco2 = rand(ceil(popsize/2),D);
    randco3 = rand(ceil(popsize/2),D);
    
    % losers learn from winners 学习更新位置、速度
    v(losers,:)=randco1.*v(losers,:)...,
        +randco2.*(p(winners,:)-p(losers,:))...,
        +phi*randco3.*(center-p(losers,:));
    p(losers,:)=p(losers,:)+v(losers,:);
    
       
    % boundary control 边界控制
    for i = 1:ceil(popsize/2)
        p(losers(i),:) = max(p(losers(i),:), (lu(1, :)));
        p(losers(i),:) = min(p(losers(i),:), (lu(2, :)));
         v(losers(i),:) = max(v(losers(i),:), (lu(1, :)));
        v(losers(i),:) = min(v(losers(i),:), (lu(2, :)));
    end
    
    % fitness evaluation
      fitness(losers,:) = SimpleBenchmark(p(losers,:),FuncId);
      [min_fitness, min_fitness_ind] = min(fitness);
      if gbestfitness > min_fitness
       gbestfitness = min_fitness;
        gbestX = p(min_fitness_ind,:);
%       else
%           gbestX= gbestX+ gbestX.*cauchy_x;
      end
      
   gbesthistory(gen)=gbestfitness;
    fprintf("CSO算法，第%d代，最佳适应度=%e\n",gen,gbestfitness);
end
  





